
/*
 * @Author: jiejie
 * @Github: https://github.com/jiejieTop
 * @LastEditTime: 2020-06-17 14:35:29
 * @Description: the code belongs to jiejie, please keep the author information and source code according to the license.
 */
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <math.h>
#include <rtthread.h>
#include <rtdevice.h>
#include <board.h>
#include "mqttclient.h"
#include "../packages/cJSON-v1.7.17/cJSON.h"
#include "temp_humi.h"
#include "icm20608_example.h"
#include "../packages/max30102-latest/examples/heart_example.h"
#include "my_mqtt.h"
#include "drv_matrix_led.h"  // 引入 LED 控制相关头文件
#include "gps_rmc.h"


#ifndef KAWAII_MQTT_HOST
#define KAWAII_MQTT_HOST               "jiejie01.top"
#endif
#ifndef KAWAII_MQTT_PORT
#define KAWAII_MQTT_PORT               "1883"
#endif
#ifndef KAWAII_MQTT_CLIENTID
#define KAWAII_MQTT_CLIENTID           "rtthread001"
#endif
#ifndef KAWAII_MQTT_USERNAME
#define KAWAII_MQTT_USERNAME           "rt-thread"
#endif
#ifndef KAWAII_MQTT_PASSWORD
#define KAWAII_MQTT_PASSWORD           "rt-thread"
#endif
#ifndef KAWAII_MQTT_SUBTOPIC
#define KAWAII_MQTT_SUBTOPIC           "rtt-sub"
#endif
#ifndef KAWAII_MQTT_PUBTOPIC
#define KAWAII_MQTT_PUBTOPIC           "rtt-pub"
#endif

#define SAMPLE_UART_NAME       "uart2"  /* 串口设备名称 */


void uart_send_A(void)
{
    rt_device_t uart_device;
    const rt_uint8_t data = 0x41; 

    // 查找串口设备
    uart_device = rt_device_find(SAMPLE_UART_NAME);
    if (uart_device == RT_NULL)
    {
        rt_kprintf("Device %s not found!\n", SAMPLE_UART_NAME);
        return;
    }
    

    // 打开设备，如果是串口设备，一般选择读写模式
    if (rt_device_open(uart_device, RT_DEVICE_FLAG_RDWR) != RT_EOK)
    {
        rt_kprintf("Failed to open %s!\n", SAMPLE_UART_NAME);
        return;
    }
    
    
    // while (1)
    // {
    //     // rt_device_write(uart_device, 0, message, rt_strlen(message));
    //     rt_device_write(uart_device, 0, &data, sizeof(data));
    //     rt_thread_mdelay(1000);   
    // }
    rt_device_write(uart_device, 0, &data, sizeof(data));
    

    // 关闭设备
    rt_device_close(uart_device);
}

void uart_send_B(void)
{
    rt_device_t uart_device;
    const rt_uint8_t data = 0x42; 

    // 查找串口设备
    uart_device = rt_device_find(SAMPLE_UART_NAME);
    if (uart_device == RT_NULL)
    {
        rt_kprintf("Device %s not found!\n", SAMPLE_UART_NAME);
        return;
    }
    

    // 打开设备，如果是串口设备，一般选择读写模式
    if (rt_device_open(uart_device, RT_DEVICE_FLAG_RDWR) != RT_EOK)
    {
        rt_kprintf("Failed to open %s!\n", SAMPLE_UART_NAME);
        return;
    }
    
    
    rt_device_write(uart_device, 0, &data, sizeof(data));
    

    // 关闭设备
    rt_device_close(uart_device);
}

void uart_send_D(void)
{
    rt_device_t uart_device;
    const rt_uint8_t data = 0x44; 

    // 查找串口设备
    uart_device = rt_device_find(SAMPLE_UART_NAME);
    if (uart_device == RT_NULL)
    {
        rt_kprintf("Device %s not found!\n", SAMPLE_UART_NAME);
        return;
    }
    

    // 打开设备，如果是串口设备，一般选择读写模式
    if (rt_device_open(uart_device, RT_DEVICE_FLAG_RDWR) != RT_EOK)
    {
        rt_kprintf("Failed to open %s!\n", SAMPLE_UART_NAME);
        return;
    }
    
    
    // while (1)
    // {
    //     // rt_device_write(uart_device, 0, message, rt_strlen(message));
    //     rt_device_write(uart_device, 0, &data, sizeof(data));
    //     rt_thread_mdelay(1000);   
    // }
    rt_device_write(uart_device, 0, &data, sizeof(data));
    

    // 关闭设备
    rt_device_close(uart_device);
}



// LED 灯带控制周期
#define LED_ON_DELAY   100  // 每个 LED 开灯的延时（毫秒）
#define LED_OFF_DELAY  100  // 每个 LED 熄灯的延时（毫秒）
#define LED_NUM        19   // LED 灯珠数量
// 声明全局变量
int switch_state = 0;  // 用来存储 switch_state 的值
int eat = 0;
int home = 0;
int music = 2;

//回调函数，用于处理接收到的 MQTT 消息
// static void sub_topic_handle1(void* client, message_data_t* msg)
// {
//     (void) client;
//     KAWAII_MQTT_LOG_I("-----------------------------------------------------------------------------------");
//     KAWAII_MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
//     KAWAII_MQTT_LOG_I("-----------------------------------------------------------------------------------");
// }

// 回调函数，用于处理接收到的 MQTT 消息
static void sub_topic_handle1(void* client, message_data_t* msg)
{
    (void) client;
    
    KAWAII_MQTT_LOG_I("-----------------------------------------------------------------------------------");
    KAWAII_MQTT_LOG_I("%s:%d %s()...\ntopic: %s\nmessage:%s", __FILE__, __LINE__, __FUNCTION__, msg->topic_name, (char*)msg->message->payload);
    KAWAII_MQTT_LOG_I("-----------------------------------------------------------------------------------");

    // 解析 JSON 消息
    char *payload = (char*)msg->message->payload;
    
    // 解析 JSON 字符串
    cJSON *root = cJSON_Parse(payload);
    if (root == NULL)
    {
        KAWAII_MQTT_LOG_E("Failed to parse JSON payload\n");
        return;
    }

    // 获取 "switch_state" 字段的值
    cJSON *switch_state_json = cJSON_GetObjectItem(root, "switch_state");
    if (switch_state_json != NULL && cJSON_IsNumber(switch_state_json))
    {
        // 提取 switch_state 的值并存储
        switch_state = switch_state_json->valueint;
        KAWAII_MQTT_LOG_I("Received switch_state: %d", switch_state);
    }
    else
    {
        KAWAII_MQTT_LOG_E("switch_state not found or not a number\n");
    }

    // 获取 "switch_state" 字段的值
    cJSON *eat_json = cJSON_GetObjectItem(root, "eat");
    if (eat_json != NULL && cJSON_IsNumber(eat_json))
    {
        // 提取 switch_state 的值并存储
        eat = eat_json->valueint;
        KAWAII_MQTT_LOG_I("Received eat: %d", eat);
    }
    else
    {
        KAWAII_MQTT_LOG_E("eat not found or not a number\n");
    }

    cJSON *home_json = cJSON_GetObjectItem(root, "home");
    if (home_json != NULL && cJSON_IsNumber(home_json))
    {
        // 提取 switch_state 的值并存储
        home = home_json->valueint;
        KAWAII_MQTT_LOG_I("Received home: %d", home);
    }
    else
    {
        KAWAII_MQTT_LOG_E("home not found or not a number\n");
    }
    cJSON *music_json = cJSON_GetObjectItem(root, "music");
    if (music_json != NULL && cJSON_IsNumber(music_json))
    {
        // 提取 switch_state 的值并存储
        music = music_json->valueint;
        KAWAII_MQTT_LOG_I("Received music: %d", music);
    }
    else
    {
        KAWAII_MQTT_LOG_E("music not found or not a number\n");
    }


    // 释放 JSON 对象
    cJSON_Delete(root);
    if(switch_state == 1)
    {
         for (int i = 0; i < LED_NUM; i++)
        {
            Set_LEDColor(i, WHITE);  // 设置第 i 个 LED 为白色
            RGB_Reflash();  // 刷新 LED 灯带显示
            rt_thread_mdelay(LED_ON_DELAY);  // 延时，模拟点亮效果
        }
    }
    else if(switch_state == 0) 
    {
        for (int i = 0; i < LED_NUM; i++)
        {
            Set_LEDColor(i, DARK);  // 设置第 i 个 LED 为暗（关闭）
            RGB_Reflash();  // 刷新 LED 灯带显示
            rt_thread_mdelay(LED_OFF_DELAY);  // 延时，模拟熄灭效果
        }
    }

    if(eat == 1)
    {
        uart_send_A();
    }
    if(home == 1)
    {
        uart_send_B();
    }
    if(music == 1)
    {
        uart_send_B();
    }
    // else if(music == 0)
    // {
    //     uart_send_D();
    // }


}

//向 MQTT 代理发布消息
static int mqtt_publish_handle1(mqtt_client_t *client)
{
    float a = sqrt(accel_x_g*accel_x_g + accel_y_g*accel_y_g + accel_z_g*accel_z_g);
    
    mqtt_message_t msg;
    memset(&msg, 0, sizeof(msg));
    
    char payload[512];  // 用于存储最终的 JSON 字符串

    //使用 snprintf 格式化数据到 JSON 字符串
    snprintf(payload, sizeof(payload), 
    "{\"temp\": %d, \"heart_rate\":%d,\"blood\":96, \"a\":%.4f, \"Speed\":%.2f, \"location\":{\"lat\":%.7f, \"lng\":%.7f}}", 
    temp, heart_rate, a, speed_value,weidu_value,jingdu_value);

    
    msg.qos = QOS0;
    msg.payload = payload;

    return mqtt_publish(client, KAWAII_MQTT_PUBTOPIC, &msg);
}

// MQTT 客户端逻辑
static void kawaii_mqtt_demo(void *parameter)
{
    mqtt_client_t *client = NULL;
    
    rt_thread_delay(6000);
    
    mqtt_log_init();

    client = mqtt_lease();

    mqtt_set_host(client, KAWAII_MQTT_HOST);
    mqtt_set_port(client, KAWAII_MQTT_PORT);
    mqtt_set_user_name(client, KAWAII_MQTT_USERNAME);
    mqtt_set_password(client, KAWAII_MQTT_PASSWORD);
    mqtt_set_client_id(client, KAWAII_MQTT_CLIENTID);
    mqtt_set_clean_session(client, 1);

    KAWAII_MQTT_LOG_I("The ID of the Kawaii client is: %s ", KAWAII_MQTT_CLIENTID);

    mqtt_connect(client);
    
    mqtt_subscribe(client, KAWAII_MQTT_SUBTOPIC, QOS0, sub_topic_handle1);
    
    while (1) {
        mqtt_publish_handle1(client);
                               
        mqtt_sleep_ms(3 * 1000);
    }
}

//启动MQTT线程
int ka_mqtt(void)
{
    rt_thread_t tid_mqtt;

    tid_mqtt = rt_thread_create("kawaii_demo", kawaii_mqtt_demo, RT_NULL, 4096, 10, 10);
    if (tid_mqtt == RT_NULL) {
        return -RT_ERROR;
    }

    rt_thread_startup(tid_mqtt);

    return RT_EOK;
}

